import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class Tab5 extends StatefulWidget {
  Tab5({Key key}) : super(key: key);

  _Tab5State createState() => _Tab5State();
}

class _Tab5State extends State<Tab5> {
  // ignore: unused_field
  WebViewController _webViewController;
  String title = "Tab5";
  @override
  Widget build(BuildContext context) {
    Future<void> evaluateJavascript() async {
      print('evaluateJavascript');
      _webViewController?.evaluateJavascript('callJS(\'visible\');');
    }

    Set<JavascriptChannel> _loadJavascriptChannel(BuildContext context) {
      final Set<JavascriptChannel> channels = Set<JavascriptChannel>();
      JavascriptChannel toastChannel = JavascriptChannel(
          name: 'Toaster',
          onMessageReceived: (JavascriptMessage message) {
            Scaffold.of(context).showSnackBar(
              SnackBar(content: Text(message.message)),
            );
          });
      JavascriptChannel changeTitle = JavascriptChannel(
          name: 'ChangeTitle',
          onMessageReceived: (JavascriptMessage message) {
            setState(() {
              title = message.message;
            });
          });
      channels.add(toastChannel);
      channels.add(changeTitle);
      return channels;
    }

    return Scaffold(
      appBar: AppBar(
        title: GestureDetector(
          child: Text(title),
          onTap: evaluateJavascript,
        ),
      ),
      body: WebView(
        // initialUrl: "https://www.jianshu.com/p/611840cc2797", //需要打开的url
        initialUrl: "http://192.168.22.121:8080", //需要打开的url
        //是否支持js 默认是不支持的，
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController controller) {
          //页面加载的时候可以获取到controller可以用来reload等操作
          _webViewController = controller;
        },
        //加载js方法到页面内，js通过此来调用flutter的方法
        javascriptChannels: _loadJavascriptChannel(context),
        onPageStarted: (String url) {},
        onPageFinished: (String url) {},
        //拦截页面url
        navigationDelegate: (NavigationRequest request) {
          if (request.url.startsWith('alipays:') ||
              request.url.startsWith('weixin:')) {
            // _openPay(context, request.url);
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      ),
    );
  }
}
